package shareTxt;

import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Random;

public class consumer {
    public static void main(String[] args) throws Exception {
        int size = 0x4;  //共享空间长度
        int position = 0; //共享空间起始位置
        int proLock = 0; //内存第0号位作为生产者标志位
        int conLock = 1; //第1位作为消费者标志位
        int ban = 2; //第2位作为禁止位
        int buf = 3; //第3位存储缓冲区大小
        byte in = 1; //1代表进入
        byte out = 0; //0代表不进入
        byte ban_pro= 1;//禁止位为1代表禁止消费者进入
        int tt=0; //记录总消费数量

        String shareFileName="data.txt";
        MappedByteBuffer mapBuf = new RandomAccessFile(shareFileName, "rw")
                .getChannel().map(FileChannel.MapMode.READ_WRITE, position, size);

        while(true){
            int temp=0;
            Thread.sleep(new Random().nextInt(1000));
            mapBuf.put(conLock,in);
            mapBuf.put(ban,ban_pro);
            while (mapBuf.get(proLock) == in && mapBuf.get(ban) == ban_pro){
                if(temp==0){System.out.println("生产者正在访问资源，消费者等待");temp=1;}
            }

            mapBuf.put(conLock,in);
            Thread.sleep(new Random().nextInt(200));
            int buffer = mapBuf.get(buf);
            if(buffer == 0){ //若缓冲池空则无法消废
                System.out.println("仓库空的，没得消费！");
            }
            else{
                buffer--;
                tt++;
                System.out.println("消费一个资源，当前库存"+buffer+"个，总共已消费"+tt+"个资源");
                mapBuf.put(buf,(byte)buffer);
            }

            mapBuf.put(conLock,out);
        }
    }
}
